package com.example.mvoidemo.flow

import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * @auth: njb
 * @date: 2024/8/11 1:39
 * @desc: 描述
 */
object FlowBus{
    private val TAG = "FlowBus"
    private val busMap = mutableMapOf<String,FlowEventBus<*>>()
    private val busStickMap = mutableMapOf<String,FlowStickEventBus<*>>()


    @Synchronized
    fun<T> with(key: String):FlowEventBus<T>{
        var eventBus = busMap[key]
        if(eventBus == null){
            eventBus = FlowEventBus<T>(key)
            busMap[key] = eventBus
        }
        return eventBus as FlowEventBus<T>
    }

    @Synchronized
    fun<T> withStick(key: String):FlowStickEventBus<T>{
        var stickEventBus = busStickMap[key]
        if (stickEventBus == null) {
            stickEventBus = FlowStickEventBus<T>(key)
            busStickMap[key] = stickEventBus
        }
        return stickEventBus as FlowStickEventBus<T>
    }

    open class FlowEventBus<T>(private val key:String):DefaultLifecycleObserver{
        private val _events: MutableSharedFlow<T> by lazy {
            obtainEvent()
        }

        private val events = _events.asSharedFlow()

        open fun obtainEvent():MutableSharedFlow<T> = MutableSharedFlow(0,1,BufferOverflow.DROP_OLDEST)


        fun register(lifecycleOwner: LifecycleOwner,action: (t:T) -> Unit){
            lifecycleOwner.lifecycleScope.launch {
                events.collect(){
                    try {
                        action(it)
                    }catch (e:Exception){
                        e.printStackTrace()
                        Log.e(TAG, "FlowBus - Error:$e")
                    }
                }
            }
        }

        fun register(scope: CoroutineScope,action: (t: T) -> Unit){
            scope.launch {
                events.collect(){
                    try {
                        action(it)
                    }catch (e:Exception){
                        e.printStackTrace()
                        Log.e(TAG, "FlowBus Scope- Error:$e")
                    }
                }
            }
        }

        suspend fun post(event:T){
            _events.emit(event)
        }

        suspend fun postScope(scope: CoroutineScope,event: T){
            scope.launch {
                _events.emit(event)
            }
        }

        override fun onDestroy(owner: LifecycleOwner) {
            super.onDestroy(owner)
            Log.w(TAG, "FlowBus ==== 自动onDestroy")
            val subscriptCount = _events.subscriptionCount.value
            if (subscriptCount <= 0)
                busMap.remove(key)
            if (subscriptCount <= 0)
                busStickMap.remove(key)
        }

        fun onDestroy(){
            Log.w(TAG, "FlowBus ==== 手动onDestroy")
            val subscriptCount = _events.subscriptionCount.value
            if (subscriptCount <= 0)
                busMap.remove(key)
            if (subscriptCount <= 0)
                busStickMap.remove(key)
        }

    }

    class FlowStickEventBus<T>(private val key: String):FlowEventBus<T>(key){
        override fun obtainEvent(): MutableSharedFlow<T> =
            MutableSharedFlow(1, 1, BufferOverflow.DROP_OLDEST)
    }
}